<template>
  <scroll-view class="viewport" enable-back-to-top scroll-y>
    <!-- 收货地址 -->
    <view class="shipment">
      <view class="user"> 当前配送点:</view>
      <view class="address"> {{ profile.addressname }}</view>
    </view>
    <!-- 商品信息 -->
    <view class="goods">
      <view v-for="item in cartList" :key="item.id" class="item">
        <image :src="item.picture" class="picture" />
        <view class="meta">
          <view class="name ellipsis"> {{ item.name }}</view>
          <view class="attrs">{{ item.mealdesc }}</view>
          <view class="prices">
            <view class="pay-price symbol">{{ priceWithDiscount(item.price, item.discount) }}</view>
            <view class="price symbol">{{ item.price }}</view>
          </view>
          <view class="count">x{{ item.count }}</view>
        </view>
      </view>
    </view>
    <!-- 配送及支付方式 -->
    <view class="related">
      <view class="item">
        <text class="text">送达时间</text>
        <view class="icon-fonts picker">{{ '11:50-12:00' }}</view>
      </view>
      <view class="item">
        <text class="text">订单备注</text>
        <!-- <input :cursor-spacing="30" class="input" placeholder="备注信息" /> -->
      </view>
      <view>
        <textarea class="notestyle" maxlength='150' v-model='noteVal' placeholder="备注信息" />
      </view>
    </view>
    <!-- 支付金额 -->
    <view class="settlement">
      <view class="item">
        <text class="text">餐品总价:</text>
        <text class="number symbol">{{ selectedCartListMoney }}</text>
      </view>
      <view class="item">
        <text class="text">配送费:</text>
        <text class="number symbol">{{ 0.0 }}</text>
      </view>
    </view>

    <view class="settlement">
      <view class="item" @click="ifpaytype=true" v-if="paytype=='wxpay'">
        <text class="text">支付方式:</text>
        <view class="number">
          <image class="imagesioc" src="/static/images/wxpai.png" />
          <text>
            微信支付 >
          </text>
        </view>
      </view>
      <view class="item" @click="ifpaytype=true" v-else>
        <text class="text">支付方式:</text>
        <view class="number">
          <image class="imagesioc" src="/static/images/moneypay.png" />
          <text>
            卡包支付 >
          </text>
        </view>

      </view>
    </view>
  </scroll-view>
  <!-- 吸底工具栏 -->
  <view :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }" class="toolbar">
    <view class="total-pay symbol">
      <text class="number">{{ Number(selectedCartListMoneyWithDiscount).toFixed(2) }}</text>
      <text class="price">¥</text>
      <text class="price">{{ selectedCartListMoney }}</text>
    </view>
    <view class="button" @tap="onOrderSubmit"> 提交订单</view>
  </view>

  <view class="buttonclase" v-if="ifpaytype">
    <view class="itemcaozuo">
      <view class="numbercaozuo">
        <text>
          支付中心
        </text>
      </view>
      <view class="numbercaozuo" @click="qvxiao">
        <view>
          <image class="imagesiocqq" src="/static/images/remor.png" />
        </view>
      </view>
    </view>

    <view class="item">
      <view class="number">
        <image class="imagesioc" src="/static/images/wxpai.png" />
        <text>
          微信支付 >
        </text>
      </view>
      <view class="number">
        <label class="radio" id='wxpay' @click="selectpay">
          <radio value="r1" :checked="paytype=='wxpay'" />选中
        </label>
      </view>
    </view>
    <view class="item">
      <view class="number">
        <image class="imagesioc" src="/static/images/moneypay.png" />
        <text>
          卡包支付 >
        </text>
      </view>
      <view class="number">
        <text style="margin-right: 20rpx;">钱包余额{{morneyval}}</text>
      </view>
      <view class="number">
        <!--  <text v-if="morneyval<selectedCartListMoneyWithDiscount">钱包余额不足</text> -->

        <label class="radio" id='moneypay' @click="selectpay">
          <radio value="r1" :checked="paytype=='moneypay'" />选中
        </label>
      </view>
    </view>
  </view>



</template>
<script lang="ts" setup>
  import {
    deleteOrderByID,
    getOrderByID,
    getPaymentDataAPI,
    postOrderAPI,
    putOrderByID,
  } from '@/services/order'
  import type { OrderCreateParams, PaymentParams } from '@/types/order'
  import { ref } from 'vue'
  import { useCartStore } from '@/stores/cart'
  import { storeToRefs } from 'pinia'
  import { useMemberStore } from '@/stores'
  import { onLoad } from '@dcloudio/uni-app'
  import { priceWithDiscount } from '@/utils/meal'


  import { onReady, onShow } from '@dcloudio/uni-app'
  import { getMoneyAPI, putMoneyAPI, gteMoneyOrderAPI } from "@/services/wallet";

  // 获取屏幕边界到安全区域距离
  const { safeAreaInsets } = uni.getSystemInfoSync()
  // 页面参数
  // const query = defineProps<{
  //   order_id ?: string
  // }>()

  const memberStore = useMemberStore()
  const { profile } = storeToRefs(memberStore)
  const cartStore = useCartStore()
  const { cartList, selectedCartListMoney, selectedCartListMoneyWithDiscount } =
    storeToRefs(cartStore)

  const paytype = ref('moneypay')

  const ifpaytype = ref(false)

  const morneyval = ref(0)

  const qvxiao = () => {
    ifpaytype.value = false
  }


  async function getmoney() {
    if (memberStore.profile) {
      const res = await getMoneyAPI()
      if (res.code == '200') {
        morneyval.value = res.data.money
      }
    }
  }

  onReady(() => {
    getmoney()
  })

  onShow(() => {
    getmoney()
  })

  // const changepay = async () => {
  //   // const res = await getMoneyAPI()
  //   // if (res.code = '200') {
  //   //   morneyval.value = Number(res.data.money)
  //   // }
  //   ifpaytype.value = true
  // }

  const selectpay = (e) => {


    if (paytype.value == 'wxpay') {
      paytype.value = 'moneypay'
    } else {
      paytype.value = 'wxpay'
    }

    ifpaytype.value = false
  }

  // 获取订单信息
  const orderPre = ref<OrderCreateParams>()
  const getMemberOrderPreData = async () => {
    if (orderId.value !== undefined) {
      const res = await getOrderByID(orderId.value)
      orderPre.value = res.result[0]
    }
  }

  // 获取订单状态
  const putMemberOrderPreData = async () => {
    if (orderId.value !== undefined) {
      const res = await putOrderByID(orderId.value, 0, Number(selectedCartListMoneyWithDiscount.value))
    }
  }

  // 删除订单
  const deletetMemberOrderPreData = async () => {
    if (orderId.value !== undefined) {
      const res = await deleteOrderByID(orderId.value)
      orderPre.value = res.result[0]
    }
  }
  // 获取支付数据
  // 获取订单信息
  const paymentdata = ref<PaymentParams>()
  const orderId = ref<string>()
  const noteVal = ref("")
  const getPaymentData = async (ismorneyBuGou ?: boolean) => {

    if (ismorneyBuGou) {
      const res = await gteMoneyOrderAPI(Number(selectedCartListMoneyWithDiscount.value) - morneyval.value);
      // console.log(res)
      //发起支付
      uni.requestPayment({
        provider: 'wxpay',
        orderInfo: res.result.orderInfo,
        timeStamp: res.result.timeStamp.toString(),
        nonceStr: res.result.nonceStr,
        package: res.result.package,
        signType: 'RSA',
        paySign: res.result.paySign,
        success: async function (res) {
          //更新订单状态为待送达

          const resw = await putOrderByID(orderId.value as string, 1, Number(morneyval.value))
          if (resw.code = '200') {

          } else {
            uni.showToast({
              title: '网络错误',
            })
            uni.navigateBack()
          }

          putMemberOrderPreData()
          // 关闭当前页，再跳转支付结果页
          uni.$emit('closeCart')
          uni.$emit('refreshMealList')
          uni.redirectTo({ url: `/pagesOrder/payment/payment?order_id=${orderId.value}` })
          console.log('success:' + JSON.stringify(res))
        },
        fail: function (err) {
          //提醒支付异常
          // 成功提示
          uni.showToast({
            title: '支付异常',
            duration: 1000,
            success: () => {
              setTimeout(() => {
                //查询订单有效性
                //deletetMemberOrderPreData()
                // 关闭当前清单，并跳转到首页
                uni.$emit('closeCart')
                uni.$emit('refreshMealList')
                uni.navigateBack()
              }, 1000)
            },
          })
          console.log('fail:' + JSON.stringify(err))
        },
      })

    } else if (orderId.value !== undefined) {
      const res = await getPaymentDataAPI(orderId.value)
      paymentdata.value = res.result
      //发起支付
      uni.requestPayment({
        provider: 'wxpay',
        orderInfo: paymentdata.value.orderInfo,
        timeStamp: paymentdata.value.timeStamp.toString(),
        nonceStr: paymentdata.value.nonceStr,
        package: paymentdata.value.package,
        signType: 'RSA',
        paySign: paymentdata.value.paySign,
        success: function (res) {
          //更新订单状态为待送达
          putMemberOrderPreData()
          // 关闭当前页，再跳转支付结果页
          uni.$emit('closeCart')
          uni.$emit('refreshMealList')
          uni.redirectTo({ url: `/pagesOrder/payment/payment?order_id=${orderId.value}` })
          console.log('success:' + JSON.stringify(res))
        },
        fail: function (err) {
          //提醒支付异常
          // 成功提示
          uni.showToast({
            title: '支付异常',
            duration: 1000,
            success: () => {
              setTimeout(() => {
                //查询订单有效性
                //deletetMemberOrderPreData()
                // 关闭当前清单，并跳转到首页
                uni.$emit('closeCart')
                uni.$emit('refreshMealList')
                uni.navigateBack()
              }, 1000)
            },
          })
          console.log('fail:' + JSON.stringify(err))
        },
      })

    }
  }



  // 提交订单
  const onOrderSubmit = async () => {
    if (profile.value !== undefined && pstime.value !== undefined) {
      const { code, result } = await postOrderAPI({
        ordertype: '午餐',
        addressid: profile.value.addressid,
        addressname: profile.value.addressname,
        mealcenterid: '',
        finallprice: Number(selectedCartListMoneyWithDiscount.value),
        pstime: pstime.value,
        meal_list: cartList.value,
        note: noteVal.value
      })
      if (code === '200') {
        cartStore.setAllPrice(Number(selectedCartListMoneyWithDiscount.value))
        orderId.value = result.orderid
        await getMemberOrderPreData()
      } else if (code === '503') {
        uni.$emit('closeCart')
        uni.$emit('refreshMealList')
        await uni.navigateBack()
        await uni.showToast({ icon: 'none', title: '部分商品不满足库存，请重新选择餐品' })
      }
    }
    let currentTime = Date.now()
    if (
      Number(orderPre.value!.expiretime) != 0 &&
      currentTime >= Number(orderPre.value!.expiretime)
    ) {
      // 成功提示
      uni.showToast({
        title: '当前订单已失效',
        duration: 1000,
        success: () => {
          setTimeout(() => {
            //删除订单
            deletetMemberOrderPreData()
            // 关闭当前清单，并跳转到首页
            uni.switchTab({
              url: '/pages/category/category',
            })
          }, 1000)
        },
      })
    }
    //开始发起支付
    else {
      //获取支付数据
      if (paytype.value == 'moneypay') {
        if (orderId.value) {

          if (morneyval.value < Number(selectedCartListMoneyWithDiscount.value)) {
            uni.showToast({
              title: `已抵扣 ${morneyval.value} 元`,
              // message: `余额不足已抵扣 ${morneyval.value} 元`,
              duration: 1000,
            })
            setTimeout(async () => {
              await getPaymentData(true)
            }, 1000)

          } else {
            const res = await putOrderByID(orderId.value, 1, Number(selectedCartListMoneyWithDiscount.value))
            if (res.code = '200') {
              uni.showToast({
                title: `支付成功`,
                duration: 1000,
              })
              setTimeout(() => {
                uni.redirectTo({ url: `/pagesOrder/payment/payment?order_id=${orderId.value}` })
              }, 1000)

            } else {
              uni.showToast({
                title: '网络错误',
              })
              uni.navigateBack()
            }
          }
        }
      } else {
        await getPaymentData()
      }

    }
  }

  const pstime = ref<string>()

  onLoad((option) => {
    if (option?.pstime !== undefined) {
      pstime.value = option.pstime
    }
  })
</script>
<style lang="scss">
  page {
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;
    background-color: #f4f4f4;
  }

  .symbol::before {
    content: '¥';
    font-size: 80%;
    margin-right: 5rpx;
  }

  .shipment {
    margin: 20rpx;
    padding: 30rpx 30rpx 30rpx 84rpx;
    font-size: 26rpx;
    border-radius: 10rpx;
    background: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/locate.png) 20rpx center / 50rpx no-repeat #fff;
    position: relative;

    .icon {
      font-size: 36rpx;
      color: #333;
      transform: translateY(-50%);
      position: absolute;
      top: 50%;
      right: 20rpx;
    }

    .user {
      color: #333;
      margin-bottom: 5rpx;
    }

    .address {
      color: #666;
    }
  }

  .goods {
    margin: 20rpx;
    padding: 0 20rpx;
    border-radius: 10rpx;
    background-color: #fff;

    .item {
      display: flex;
      padding: 30rpx 0;
      border-top: 1rpx solid #eee;

      &:first-child {
        border-top: none;
      }

      .picture {
        width: 170rpx;
        height: 170rpx;
        border-radius: 10rpx;
        margin-right: 20rpx;
      }

      .meta {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        position: relative;
      }

      .name {
        height: 80rpx;
        font-size: 26rpx;
        color: #444;
      }

      .attrs {
        line-height: 1.8;
        padding: 0 15rpx;
        margin-top: 6rpx;
        font-size: 24rpx;
        align-self: flex-start;
        border-radius: 4rpx;
        color: #888;
        background-color: #f7f7f8;
      }

      .prices {
        display: flex;
        align-items: baseline;
        margin-top: 6rpx;
        font-size: 28rpx;

        .pay-price {
          margin-right: 10rpx;
          color: #cf4444;
        }

        .price {
          font-size: 24rpx;
          color: #999;
          text-decoration: line-through;
        }
      }

      .count {
        position: absolute;
        bottom: 0;
        right: 0;
        font-size: 26rpx;
        color: #444;
      }
    }
  }

  .related {
    margin: 20rpx;
    padding: 0 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
    padding-bottom: 10rpx;

    .item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      min-height: 80rpx;
      font-size: 26rpx;
      color: #333;
    }

    .input {
      flex: 1;
      text-align: right;
      margin: 20rpx 0;
      font-size: 26rpx;
      color: #999;
    }

    .item .text {
      width: 125rpx;
    }

    .picker {
      color: #666;
    }
  }

  /* 结算清单 */
  .settlement {
    margin: 20rpx;
    padding: 0 20rpx;
    border-radius: 10rpx;
    background-color: #fff;

    .item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 80rpx;
      font-size: 26rpx;
      color: #333;
    }

    .danger {
      color: #cf4444;
    }
  }

  /* 吸底工具栏 */
  .toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: calc(var(--window-bottom));
    z-index: 1;

    background-color: #fff;
    height: 100rpx;
    padding: 0 20rpx;
    border-top: 1rpx solid #eaeaea;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: content-box;

    .total-pay {
      font-size: 40rpx;
      color: #cf4444;

      .price {
        font-size: 24rpx;
        color: #999;
        text-decoration: line-through;
      }

      .decimal {
        font-size: 75%;
      }
    }

    .button {
      width: 220rpx;
      text-align: center;
      line-height: 72rpx;
      font-size: 26rpx;
      color: #fff;
      border-radius: 72rpx;
      background-color: #27ba9b;
    }

    .disabled {
      opacity: 0.6;
    }
  }

  .notestyle {
    height: 150rpx;
    // width: 650rpx;
    // border: 1px black solid;
  }

  .imagesioc {
    width: 60rpx;
    height: 60rpx;
  }

  .imagesiocqq {
    width: 40rpx;
    height: 40rpx;
  }

  .buttonclase {
    z-index: 100;
    background-color: #ffffff;
    border: #f7f7f7 1px solid;
    width: 97%;
    margin: auto;
    border-radius: 10px;
    margin-bottom: 15px;

    .item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 80rpx;
      font-size: 26rpx;
      color: #333;
      padding-left: 20px;
      padding-right: 20px;
      margin-bottom: 10px;
    }

    .danger {
      color: #cf4444;
    }

    .itemcaozuo {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 80rpx;
      font-size: 26rpx;
      color: #333;
      padding-left: 20px;
      padding-right: 20px;
      margin-bottom: 10px;
      background-color: #cfcfcf;
      border-radius: 10px 10px 0 0;

    }
  }
</style>
